import { login } from '@/api/login';
import router from "@/router/index";


export default {
    state: {
        //用户的token
        token:localStorage.getItem(process.env.VUE_APP_TOKEN_NAME)||'',
        //用户的相关信息
        userInfo:(JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_INFO)))||{},
        //判断用户是否处于登录状态
        isLogin:localStorage.getItem(process.env.VUE_ADMIN_ISLOGIN)||false,
        // 是否动态添加路由
        isDynamicAddedRoute: false,
        // 用户的菜单列表数据
        menuList:JSON.parse(localStorage.getItem(process.env.VUE_APP_MENU_LIST)) || [],
        menuUrls:JSON.parse(localStorage.getItem(process.env.VUE_APP_MENU_URLS)) || [],
    },
    getters: {},
    mutations: {
        //保存token令牌
        saveToken(state,data){
           state.token=data;
           localStorage.setItem(process.env.VUE_APP_TOKEN_NAME,state.token)
        },
        //保存用户信息
        updateuserInfo(state,data){
            state.userInfo=data;
            localStorage.setItem(process.env.VUE_APP_USER_INFO,JSON.stringify(state.userInfo));
        },
        //退出登录
        logout(state){
             state.isLogin=false;
             localStorage.removeItem(process.env.VUE_ADMIN_ISLOGIN);
             state.token='';
             localStorage.removeItem(process.env.VUE_APP_TOKEN_NAME);
             state.menuList=[];
             localStorage.removeItem(process.env.VUE_APP_MENU_LIST);
             state.menuUrls=[];
             localStorage.removeItem(process.env.VUE_APP_MENU_URLS);
        },
        setLoginState(state,flag){
            state.isLogin=flag;
            localStorage.setItem('VUE_ADMIN_ISLOGIN',flag)
        },
        //保存权限列表
        setMenuList(state,menuList){
            state.menuList=menuList;
            localStorage.setItem(process.env.VUE_APP_MENU_LIST,JSON.stringify(menuList));
        },
        //保存权限菜单
        setMenuUrls(state,menuUrls){
            state.menuUrls=menuUrls;
            localStorage.setItem(process.env.VUE_APP_MENU_URLS,JSON.stringify(menuUrls));
        },
        //是否加载动态路由
        isLoadAsyncRoute(state,flag){
            state.isDynamicAddedRoute=flag;
        }
    },
    actions: {
        //登录相关
        async loginAction(context,data){ 
           console.log(context) 
           try {
                let res= await login(data)
                console.log(res);
                context.commit('saveToken',res.list.token)
                context.commit('updateuserInfo',{
                    menus:res.list.menus,
                    menu_url:res.list.menus_url,
                    username:res.list.username
                });
                //设置用户的登录状态为true
                context.commit("setLoginState", true);
                //登录成功之后,需要根据后台返回的菜单数据来动态添加路由
                context.dispatch("loadAsyncRoute");
               return true;  
           } catch (error) {
               return Promise.reject(error);
           } 
        },
        loadAsyncRoute(context){
            //定义保存前端所需要的所有路由的数组
            const allRoutes=[];
            //递归获取router/modules目录下的所有以.js文件结尾的暴露出来的模块
            const routerFiles=require.context('@/router/modules',true,/\.js/);
            //获取前端需要加载的所有权限路由
            //console.log('###',routerFiles.keys()) // ['./dashboard.js', './mall.js', './system.js']
            routerFiles.keys().forEach(key => {
                const route=require('@/router/modules'+key.split('.')[1]);
                allRoutes.push(...route.default);
            });
            //获取后端返回的权限菜单
            // console.log('前端所需权限菜单',allRoutes)
            // console.log('后端返回的权限菜单',context.state.userInfo.menu_url);
            const menu_url=context.state.userInfo.menu_url;
            // 过滤出需要权限的路由
            const asyncRoutes=allRoutes.filter(item=>menu_url.includes(item.path));
            // console.log(asyncRoutes);
            // 将这些路由动态加载到系统中
            allRoutes.forEach(route=>{
                //将过滤好的路由加载到layout路由中去
                router.addRoute('layout',route)
            })
            context.commit('isLoadAsyncRoute',true);
        }
    }
};